package com.example.waterdispenserm2.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.waterdispenserm2.app.LPHYApplication;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityMainBinding;
import com.example.waterdispenserm2.inter.MainInterface;
import com.example.waterdispenserm2.inter.MainInterfaceUtil;
import com.example.waterdispenserm2.vmc.CommandBuilder;
import com.example.waterdispenserm2.vmc.DataParser;
import com.example.waterdispenserm2.adapter.ErrorAdapter;
import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.util.SPUtils;
import com.example.waterdispenserm2.vmc.SerialService;

public class MainActivity extends BasicsActivity<ActivityMainBinding> implements MainInterface {

    public static  void startActivity(){
        Intent intent=new Intent(SPUtils.getContext(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        SPUtils.getContext().startActivity(intent);
    }




    // 广播接收器
    private final BroadcastReceiver dataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("SERIAL_DATA_UPDATE".equals(intent.getAction())) {
                // 更新UI数据
                DataParser.DeviceData data = (DataParser.DeviceData) intent.getSerializableExtra("data");
                updateUI(data);
            } else if ("SERIAL_STATUS_UPDATE".equals(intent.getAction())) {
                // 更新连接状态
                boolean connected = intent.getBooleanExtra("connected", false);
                MainInterfaceUtil.doCallBackUpdateConnectionStatus(connected);
               // updateConnectionStatus(connected);
            }
        }
    };

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    public void initView() {
        MainInterfaceUtil.setM2Interface(this);
        // 初始化UI组件
        initUIComponents();

        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction("SERIAL_DATA_UPDATE");
        filter.addAction("SERIAL_STATUS_UPDATE");
        registerReceiver(dataReceiver, filter);

        if (!TextUtils.isEmpty(binding.etAdd.getText().toString().trim())) {
            // 绑定服务
            binding.btOpen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        if ("0".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS0");
                        } else if ("1".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS1");
                        } else if ("2".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS2");
                        } else if ("3".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS3");
                        } else if ("4".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS4");
                        } else if ("5".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS5");
                        } else if ("6".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS6");
                        } else if ("7".equals(binding.etAdd.getText().toString().trim())) {
                            SPUtils.setSerialPort("/dev/ttyS7");
                        }
                        Intent serviceIntent = new Intent(SPUtils.getContext(), SerialService.class);
                        bindService(serviceIntent, LPHYApplication.connection, Context.BIND_AUTO_CREATE);

                }
            });
        }
        binding.btClase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LPHYApplication.serialService.onDestroy();
            }
        });


        if (SPUtils.getSerialPortNum().contains("0")){
            binding.etAdd.setText("0");
        }
        if (SPUtils.getSerialPortNum().contains("1")){
            binding.etAdd.setText("1");
        }
        if (SPUtils.getSerialPortNum().contains("2")){
            binding.etAdd.setText("2");
        }
        if (SPUtils.getSerialPortNum().contains("3")){
            binding.etAdd.setText("3");
        }
        if (SPUtils.getSerialPortNum().contains("4")){
            binding.etAdd.setText("4");
        }
        if (SPUtils.getSerialPortNum().contains("5")){
            binding.etAdd.setText("5");
        }
        if (SPUtils.getSerialPortNum().contains("6")){
            binding.etAdd.setText("6");
        }
        if (SPUtils.getSerialPortNum().contains("7")){
            binding.etAdd.setText("7");
        }


    }


    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(LayoutInflater.from(this));
    }


    /**
     * 初始化UI组件
     */
    private void initUIComponents() {
        binding.ivMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        // 设置监听器
        binding.tempSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                binding.tvTempValue.setText(progress + "℃");
            }
            @Override public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        binding.btnTempDown.setOnClickListener(v -> {
            int progress = binding.tempSeekbar.getProgress() - 5;
            binding.tempSeekbar.setProgress(Math.max(35, progress));
        });

        binding.btnTempUp.setOnClickListener(v -> {
            int progress = binding.tempSeekbar.getProgress() + 5;
            binding.tempSeekbar.setProgress(Math.min(98, progress));
        });

        binding.btnWaterDown.setOnClickListener(v -> {
            int volume = Integer.parseInt(binding.etWaterVolume.getText().toString()) - 100;
            binding.etWaterVolume.setText(String.valueOf(Math.max(30, volume)));
        });

        binding.btnWaterUp.setOnClickListener(v -> {
            int volume = Integer.parseInt(binding.etWaterVolume.getText().toString()) + 100;
            binding.etWaterVolume.setText(String.valueOf(Math.min(3000, volume)));
        });

        binding.btnStartWater.setOnClickListener(v -> {
            int temp = binding.tempSeekbar.getProgress();
            int volume = Integer.parseInt(binding.etWaterVolume.getText().toString());
            int normal= binding.switchNormal.isChecked() ? 1 : 0;
            if (LPHYApplication.bound) {
                LPHYApplication.serialService.sendWaterCommand(true, temp, volume,normal);
            }else {
                Toast.makeText(MainActivity.this,"上位机尚未与下位机连接",Toast.LENGTH_LONG).show();
            }
        });

        binding.btnStopWater.setOnClickListener(v -> {
            if (LPHYApplication.bound) {
                LPHYApplication.serialService.sendWaterCommand(false, 0, 0,0);
            }else {
                Toast.makeText(MainActivity.this,"上位机尚未与下位机连接",Toast.LENGTH_LONG).show();
            }
        });
        binding.btnApplyOutput.setOnClickListener(v -> applyOutputSettings());
        binding.btRefreshCumulativeData.setOnClickListener(v -> refreshCumulativeData());
        binding.btQueryErrorInformation.setOnClickListener(v -> queryErrorInfo());
    }

    /**
     * 应用输出设置
     */
    private void applyOutputSettings() {
        CommandBuilder.OutputConfig config = new CommandBuilder.OutputConfig();
        int out1Id =binding.rgOut1.getCheckedRadioButtonId();
        if (out1Id == R.id.rb_out1_half) {
            config.output1 = 0x01; // 半驱
        } else if (out1Id == R.id.rb_out1_full) {
            config.output1 = 0x03; // 全驱
        }
        int valveId = binding.rgValve.getCheckedRadioButtonId();
        if (valveId == R.id.rb_valve_half) {
            config.output2 = 0x01; // 半驱
        } else if (valveId == R.id.rb_valve_full) {
            config.output2 = 0x03; // 全驱
        }
        int flushId = binding.rgFlush.getCheckedRadioButtonId();
        if (flushId == R.id.rb_flush_half) {
            config.output3 = 0x01; // 半驱
        } else if (flushId == R.id.rb_flush_full) {
            config.output3 = 0x03; // 全驱
        }
        config.output4 = (byte) (binding.switchPump.isChecked() ? 0x01 : 0x00);

        if (LPHYApplication.bound) {
            LPHYApplication.serialService.sendOutputCommand(config);
        }else {
            Toast.makeText(MainActivity.this,"上位机尚未与下位机连接",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 刷新累计数据
     */
    private void refreshCumulativeData() {
        if (LPHYApplication.bound) {
            LPHYApplication.serialService.querySummaryData();
        }else {
            Toast.makeText(MainActivity.this,"上位机尚未与下位机连接",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 查询错误信息
     */
    private void queryErrorInfo() {
        if (LPHYApplication.bound) {
            LPHYApplication.serialService.queryErrorInfo();
        }else {
            Toast.makeText(MainActivity.this,"上位机尚未与下位机连接",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 更新UI显示
     * @param data 设备数据
     */
    @SuppressLint("SetTextI18n")
    private void updateUI(DataParser.DeviceData data) {
        // 更新实时数据
        binding.tvCurrentTemp.setText(data.currentTemp + "℃");
        binding.tvCurrentVolume.setText(data.currentVolume + "ml");
        // 更新I/O状态指示灯
        updateIndicator(binding.ivIn1, data.input1);
        updateIndicator(binding.ivIn2, data.input2);
        updateIndicator(binding.ivIn3, data.input3);
        updateIndicator(binding.ivIn4, data.input4);
        updateIndicator(binding.ivOut1, data.output1);
        updateIndicator(binding.ivOut2, data.output2);
        updateIndicator(binding.ivOut3, data.output3);
        updateIndicator(binding.ivOut4, data.output4);
        // 更新累计数据
        binding.tvTotalWaterOutput.setText(data.totalWater + "ml");
        binding.tvHeatingFrequency.setText(data.heatingCount + "次");
        binding.tvWorkingHours.setText(formatTime(data.workingTime));

        // 更新错误信息 (需要自定义Adapter)
        if (data.historyErrors != null) {
            // 这里需要实现错误列表的适配器lv_historical_error_records
            binding.tvNotData.setVisibility(View.GONE);
            binding.lvHistoricalErrorRecords.setVisibility(View.VISIBLE);
            binding.lvHistoricalErrorRecords.setAdapter(new ErrorAdapter(this,data.historyErrors));
        }else {
            binding.lvHistoricalErrorRecords.setVisibility(View.GONE);
            binding.tvNotData.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新指示灯状态
     * @param view 指示灯视图
     * @param active 是否激活
     */
    private void updateIndicator(ImageView view, boolean active) {
        view.setImageResource(active ? R.drawable.led_on : R.drawable.led_off);
    }

    /**
     * 格式化时间显示
     * @param seconds 总秒数
     * @return 格式化后的时间字符串
     */
    @SuppressLint("DefaultLocale")
    private String formatTime(long seconds) {
        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        long secs = seconds % 60;
        return String.format("%02d:%02d:%02d", hours, minutes, secs);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播
        unregisterReceiver(dataReceiver);
    }
    /**
     * 更新连接状态显示
     * @param status 是否已连接
     */
    @Override
    public void updateConnectionStatus(boolean status) {
        binding.tvConnection.setText(status ? "已连接" : "已断开");
        binding.tvConnection.setTextColor(status ?
                getResources().getColor(android.R.color.white) :
                getResources().getColor(android.R.color.holo_red_dark));
    }
}